package cn.anosi.utils;

import cn.anosi.exception.CustomException;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;

/**
 * excel 操作工具类
 * @author admin
 *
 */
public class ExcelUtils {
	/**
	 * 单行默认表头
	 * @param workbook
	 * @param sheet
	 * @param title
	 * @return
	 */
	public static HSSFRow setDefaultHead(HSSFWorkbook workbook, HSSFSheet sheet, String[] title){
		if(null == workbook || null == sheet || null == title || title.length <= 0){
			throw new CustomException("表头创建异常");
		}
		
		HSSFRow headRow = sheet.createRow(0);
		
		//字体
		HSSFFont font = workbook.createFont();
		font.setFontHeightInPoints((short) 10);//默认为10
		
		
		//单元格样式
		HSSFCellStyle style = workbook.createCellStyle();
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);    
		style.setFillForegroundColor(HSSFColor.YELLOW.index); //颜色
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
		style.setFont(font); //设置字体
		
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框    
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框    
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框    
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框   
		
		
		for(int i = 0; i < title.length; i++){
			HSSFCell cell = headRow.createCell(i);
			cell.setCellValue(title[i]);
			cell.setCellStyle(style);
		}
		return headRow;
	}
	
	/**
	 * 单行表头
	 * @param workbook
	 * @param sheet
	 * @param title  表头内容
	 * @param fointSize 字体大小
	 * @param width 宽度，单位：字符数
	 * @return
	 */
	public static HSSFRow setSingleHead(HSSFWorkbook workbook, HSSFSheet sheet, String[] title, Integer fointSize, Integer[] width){
		if(null == workbook || null == sheet || null == title || title.length <= 0){
			throw new CustomException("表头创建异常");
		}
		
		HSSFRow headRow = sheet.createRow(0);
		
		//字体
		HSSFFont font = workbook.createFont();
		if(null != fointSize){
			font.setFontHeightInPoints((short) fointSize.intValue());//设置字体大小
		}else{
			font.setFontHeightInPoints((short) 10);//默认为10
		}
		
		//单元格样式
		HSSFCellStyle style = workbook.createCellStyle();
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);    
		style.setFillForegroundColor(HSSFColor.YELLOW.index); //颜色
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
		style.setFont(font); //设置字体
		
		
		for(int i = 0; i < title.length; i++){
			HSSFCell cell = headRow.createCell(i);
			//设置列宽
			if(null != width && null != width[i]){
				sheet.setColumnWidth(i, width[i] * 256);
			}
			cell.setCellValue(title[i]);
			cell.setCellStyle(style);
		}
		return headRow;
	}
	
	
	
}
